//
//  PGMediaViewController.m
//  PhotographicGuide
//
//  Created by indream on 13-2-13.
//  Copyright (c) 2013年 indream. All rights reserved.
//

#import "PGMediaViewController.h"
#import "PGArticleManager.h"
#import "PGLocalFileManager.h"
#import "MobClick.h"
#import <QuartzCore/QuartzCore.h>
static NSString*NOTIFICATION_PHOTO_LOADED=@"__NOTIFICATION_PHOTO_LOADED__";
@interface PGMediaViewController ()

@end

@implementation PGMediaViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.view.transform = CGAffineTransformMakeRotation(-M_PI/2.0);
    [[UIApplication sharedApplication]setStatusBarHidden:YES];
    [MobClick beginLogPageView:[NSString stringWithFormat:@"media=%d",_articleId]];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication]setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    [MobClick endLogPageView:[NSString stringWithFormat:@"media=%d",_articleId]];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    CGRect rect = self.activityIndicator.frame;
    rect.origin.x = [UIScreen mainScreen].bounds.size.height/2.0-rect.size.height/2.0;
    rect.origin.y = [UIScreen mainScreen].bounds.size.width/2.0-rect.size.width/2.0;
    self.activityIndicator.frame = rect;
    [self.activityIndicator startAnimating];
    [self loadImage:self.url];
    self.titleLabel.text = self.title;
    // Do any additional setup after loading the view from its nib.
}
-(void)refresh{
    
    self.imageView.image = [UIImage imageWithData:[[PGLocalFileManager sharedManager]fileWithURL:_url]];
    if(self.imageView.image==nil||[[PGLocalFileManager sharedManager] isJPEGValid:_url]!=0){
        [[PGLocalFileManager sharedManager] removeFileWithURL:_url];
    }
    [self.activityIndicator stopAnimating];
    if(_imageView.image==nil){
        return;
    }
    _scrollView.minimumZoomScale = 1.0;   //最小倍数
    _scrollView.maximumZoomScale = self.imageView.image.size.width/SCREEN_HEIGHT;  //最大倍数
    _scrollView.maximumZoomScale = _scrollView.maximumZoomScale<1?1.0:_scrollView.maximumZoomScale;
    _scrollView.contentSize = CGSizeMake(SCREEN_HEIGHT,SCREEN_WIDTH); //两倍大小图片
    //_imageView.image.size.height/_imageView.image.size.width*SCREEN_HEIGHT
    
    _scrollView.delegate = self;
    _scrollView.decelerationRate = 1.0f;
    CGRect rect = _imageView.frame;
    rect.size.width = SCREEN_HEIGHT;
    rect.size.height = _imageView.image.size.height/_imageView.image.size.width*SCREEN_HEIGHT;
    
    _imageView.frame = rect;

    _scrollView.zoomScale = 1.0;
    [self scrollViewDidZoom:_scrollView];
}
-(void)loadImage:(NSString*)url{
    if([url componentsSeparatedByString:@"http://"].count<2){
        [self.activityIndicator stopAnimating];
        return;
    }
    self.url = url;
    if([[PGLocalFileManager sharedManager]fileIsExist:url]){
        [self performSelector:@selector(refresh) withObject:nil afterDelay:0.3];
    }else{
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(imageLoaded:) name:NOTIFICATION_PHOTO_LOADED object:nil];
        [[PGArticleManager sharedManager]addQperator:[[PGHttpOperator alloc]initWithURLString:url cache:YES notification:NOTIFICATION_PHOTO_LOADED]];
    }
}
-(void)imageLoaded:(NSNotification*)notification{
    if([[notification.userInfo objectForKey:@"url"]isEqualToString:self.url]){
        [[NSNotificationCenter defaultCenter]removeObserver:self name:NOTIFICATION_PHOTO_LOADED object:nil];
        if([[PGLocalFileManager sharedManager]fileIsExist:[notification.userInfo objectForKey:@"url"]]){
            
        }else{
            if([[PGLocalFileManager sharedManager] saveFile:
                [notification.userInfo objectForKey:@"data"]
                                                withFileURL:[notification.userInfo objectForKey:@"url"]]){
                
                self.imageView.image = [UIImage imageWithData:[[PGLocalFileManager sharedManager]fileWithURL:_url]];
            }
        }
        [self refresh];
    }
}
-(void)scrollViewDidZoom:(UIScrollView *)scrollView{
    
    CGFloat t_zs = scrollView.zoomScale;
    t_zs = MAX(t_zs, 0.9f);
    t_zs = MIN(t_zs, 5.0f);
    
    CGFloat x = scrollView.frame.size.width/2;
    CGFloat y = scrollView.frame.size.height/2;
    
    x = scrollView.contentSize.width > scrollView.frame.size.width? scrollView.contentSize.width/2: x;
    y = scrollView.contentSize.height > scrollView.frame.size.height? scrollView.contentSize.height/2: y;
    
    [self.imageView setCenter:CGPointMake(x, y)];
    
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return _imageView;
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)backHandle:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)saveHandle:(id)sender {
    if(self.imageView.image!=nil){
        UIImageWriteToSavedPhotosAlbum(self.imageView.image,self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);
    }
}
- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    UIAlertView *alert ;
    if(!error){
         alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"图片已保存至相册" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];
    }else{
         alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"图片保存失败" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];[UIView beginAnimations:@"" context:nil];
        
    }
    self.rotaAlert = alert;
    self.rotaAlert.hidden = YES;
    [self.rotaAlert show];
}

- (void)didPresentAlertView:(UIAlertView *)alertView

{
    self.rotaAlert.transform = CGAffineTransformMakeRotation(-M_PI / 2);
    self.rotaAlert.hidden =NO;
}



- (void)viewDidUnload {
    [self setNavBarView:nil];
    [self setImageView:nil];
    [self setScrollView:nil];
    [self setActivityIndicator:nil];
    [self setTitleLabel:nil];
    [super viewDidUnload];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [_navBarView setHidden:!_navBarView.hidden];
}
@end
